#pragma once

#include<iostream>
#include<string>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/stat.h>

#include"../Com/Util.hpp"
#include"../Com/Log.hpp"

namespace ns_compiler
{
    using namespace ns_Util;
    using namespace ns_LOG;

    class compiler
    {
        public:
            compiler(){}
            ~compiler(){}
            static bool Compile(const std::string &file_name)
            {
                pid_t pid = fork();
                if(pid < 0)
                {
                    LOG(ERROR) << "fork error" << "\n";
                    return false;
                }
                else if(pid == 0)
                {
                    //创建并打开保留错误信息的文件
                    umask(0);
                    int _stderr = open(PathUtil::COMPILERERR(file_name).c_str(),O_CREAT | O_WRONLY,0644);
                    if(_stderr < 0)
                    {
                        LOG(WARNING) << "open error" << "\n";
                        exit(1);
                    }

                    //将异常信息全部写进自定义文件
                    dup2(_stderr,2);

                    //程序替换子进程进行编译
                    execlp("g++", "g++", "-o", PathUtil::EXE(file_name).c_str(),\
                        PathUtil::SRC(file_name).c_str(), "-D", "COMPILER_ONLINE","-std=c++11",  nullptr/*不要忘记*/);
                    exit(1);
                }
                else
                {
                    waitpid(pid,nullptr,0);
                    if(FileUtil::ISFILEEXIT(PathUtil::EXE(file_name)))
                    {
                        LOG(INFO) << "compile success" << "\n";
                        return true;
                    }
                }

                LOG(ERROR) << "compile error" << "\n";
                return false;
            }
        private:
    };
}